<template>
  <div style="padding: 0 15px;">

    <el-steps :active="0" simple style="margin-top: 20px">
      <el-step title="类目选择" icon="el-icon-receiving" />
      <el-step title="添加属性" icon="el-icon-s-operation" />
      <el-step title="添加图片" icon="el-icon-picture-outline" />
      <el-step title="添加详情" icon="el-icon-notebook-2" />
    </el-steps>

    <div class="box">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        当前类目：{{ ruleForm.categoryName }}
        <br>
        <el-cascader-panel
          ref="cascader"
          v-model="ruleForm.parentId"
          style="margin-top: 15px"
          filterable
          placeholder="试试 搜索关键字"
          :props="props"
          @change="handleCategoryChange"
        />

        <div class="divider" />

        <el-button
          type="primary"
          @click="submitForm('ruleForm')"
        >下一步，添加商品属性</el-button>
      </el-form>
    </div>
  </div>
</template>
<script>
import LocalStorage from '@/utils/StorageUtils.js'
import * as categoryApi from '@/api/category'

export default {
  data() {
    return {
      ruleForm: {
        name: '',
        typeNumber: '',
        title: '',
        discription: '',
        listPrice: 0.0,
        stock: 0,
        stockThreshold: 0,
        unit: '',
        brandId: 0,
        categoryId: 0,
        categoryName: '', // 客户端显示的类别名称，服务器端不需要
        albumId: 0,
        pictures: [],
        keywords: '',
        tags: '',
        sort: 10,
        detail: '',
        parentId: [0] // 默认父类别为根类别
      },
      rules: {
        parentId: [
          { required: true, message: '必须选择商品类别', trigger: 'blur' }
        ]
      },
      props: {
        lazy: true, // 懒加载
        emitPath: false, // 设置 false，只返回该节点的值
        lazyLoad: (node, resolve) => {
          // node 是被选定是节点，resolve是一个回调函数，用于将数据返回给组件
          /** 定义懒加载方式 */
          console.log('选择的当前节点：', node)
          let parentId = 0
          // 当时被点击的节点不是根节点时，parentId为当前节点的id
          if (!node.root) {
            parentId = node.data.value
          }
          categoryApi.queryByParentId(parentId).then((res) => {
            console.log('加载子类别：', res)
            const children = res.data
            // 整理数据结构, 返回类别数组 [{label:'类别名', value:'类别id'}...]
            const nodes = []
            children.forEach((category) => {
              nodes.push({
                label: category.name, // 类别名称
                value: category.id, // 类别id
                leaf: category.isParent !== 1 // 是否为叶子节点
              })
            })
            console.log('整理后的类别数组：', nodes)
            // 将数据返回给组件
            resolve(nodes)
          })
        }
      }
    }
  },

  /** 页面挂载完毕后执行 */
  mounted() {
    // 加载上一步的spu数据
    const form = LocalStorage.get(LocalStorage.KEY_ADD_SPU)
    if (form) {
      this.ruleForm = form
    }
  },

  methods: {
    /** 提交表单
            在此设计完整商品表单数据格式，将信息缓存到window.sessionStorage中，继续下一步.
            数据格式如下：
            {
                categoryId:1,
                categoryInfo: '父类别/子类别/孙子类别',
                ....
            }
    */
    handleCategoryChange(value) {
      // value 是选定的 categoryId
      console.log('选择的类别：', value)
      this.ruleForm.categoryId = value
      this.ruleForm.categoryName = this.pathName('cascader')
    },
    pathName(cascaderName) {
      const selectedNode = this.$refs['cascader'].getCheckedNodes()[0]
      console.log('选定的节点：', selectedNode)
      // 从选定的列别节点 递归获取全部父节点路径
      if (!selectedNode) {
        return ''
      }
      let path = selectedNode.data.label
      let parent = selectedNode.parent
      while (parent) {
        path = parent.data.label + '/' + path
        parent = parent.parent
      }
      return path
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 整理数据结构， 缓存到sessionStorage
          // this.ruleForm.categoryId = this.ruleForm.parentId
          // 缓存冗余字段：categoryName
          // this.ruleForm.categoryName = this.$refs['cascader'].getCheckedNodes()[0].data.label
          LocalStorage.save(LocalStorage.KEY_ADD_SPU, this.ruleForm)
          // 下一步
          this.$router.push('/spu/step2')
        }
      }).catch((err) => {
        console.log('表单验证失败：', err)
      })
    }
  }
}
</script>
